<template>
  <div class="supplierPerson">
    <pageCard :title-name="'联系人'" :type="'pageTitle'">
      <template #header>
        <i class="el-icon-close closeIcon" @click="pageClose" />
      </template>
      <div class="topText">姓名：</div>
      <el-input v-model="search.personName" placeholder="请输入" class="searchInput" style="width: 150px" />
      <el-button type="primary" class="topBtn" icon="el-icon-search" @click="searchClick">搜索</el-button>
      <div class="topBtnDiv">
        <el-button
          v-permission="['system:supplier:addPerson']"
          type="primary"
          plain
          class="topBtn"
          @click="alertForm('add')"
        >
          新增
        </el-button>
      </div>
      <myTable
        ref="myTable"
        style="height: 100%"
        :row-key="'personId'"
        :table-label="tableLabel"
        :table-data="tableData"
        :table-total-size="tableTotalSize"
        :search-data="searchData"
        @getTableData="getTableData"
        @handleSelectionChange="handleSelectionChange"
        @rowClickChange="rowClickChange"
      >
        <template #operating="slotProps">
          <el-link
            v-permission="['system:supplier:editPerson']"
            :underline="false"
            type="primary"
            @click="alertForm('edit')"
          >
            修改
          </el-link>
          <el-link
            v-permission="['system:supplier:delPerson']"
            :underline="false"
            type="danger"
            @click="deleteClick()"
          >
            删除
          </el-link>
          <!-- <p>{{ slotProps.propValue }}</p> -->
        </template>
      </myTable>
      <pagination
        :table-total-size="tableTotalSize"
        :search-data="searchData"
        @getTableData="$refs.myTable.getTableData()"
      />
    </pageCard>
    <el-dialog
      v-if="dialogVisible"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="35%"
      @close="closeDialog()"
    >
      <el-form ref="formData" :model="formData" :rules="rules" label-width="100px" style="padding: 0px 40px">
        <el-form-item label="姓名：" prop="personName">
          <el-input
            v-model="formData.personName"
            maxlength="50"
            show-word-limit
            class="show-word-limit"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="岗位：">
          <el-input
            v-model="formData.post"
            placeholder="请输入岗位"
            maxlength="200"
            show-word-limit
            class="show-word-limit-52"
          />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input
            v-model="formData.email"
            maxlength="100"
            show-word-limit
            class="show-word-limit-52"
            placeholder="请输入邮箱地址"
          />
        </el-form-item>
        <el-form-item label="移动电话：" prop="mobileTel">
          <el-input v-model="formData.mobileTel" placeholder="请输入移动电话号码" type="tel" />
        </el-form-item>
        <el-form-item label="固定电话：" prop="telephone">
          <el-input
            v-model="formData.telephone"
            maxlength="50"
            show-word-limit
            class="show-word-limit"
            placeholder="请输入固定电话号码"
          />
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model="formData.userNote"
            maxlength="255"
            show-word-limit
            type="textarea"
            :rows="2"
            class="show-word-limit"
            :autosize="{ minRows: 2 }"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="性别：">
          <el-radio v-model="formData.sex" label="男">男</el-radio>
          <el-radio v-model="formData.sex" label="女">女</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pageCard from '@/components/page/pageCard'
import myTable from '@/components/Table/index'
import pagination from '@/components/Table/pagination'
import { addClientPerson, editClientPerson, deleteClientPerson } from '@/api/system-management'
import { getClientPerson } from '@/api/table'
import { ValidPhone } from '@/utils/validate'
const validPhone = (rule, value, callback) => {
  console.log(rule)
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!ValidPhone(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}
export default {
  name: 'SupplierPerson',
  components: {
    pageCard,
    myTable,
    pagination
  },
  props: {
    currentSupplier: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      dialogTitle: '联系人',
      formDialogType: '',
      dialogVisible: false,
      // 表单数据
      formData: {
        personId: null,
        personName: '',
        post: '',
        email: '',
        mobileTel: null,
        telephone: null,
        userNote: '',
        sex: ''
      },
      rules: {
        personName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
        mobileTel: [{ required: true, validator: validPhone, trigger: 'blur' }]
      },
      // 主页面数据
      search: {
        personName: '',
        chooseDate: null
      },
      searchData: {
        pageSize: 10,
        currentPage: 1,
        sort: {},
        params: {}
      },
      // table需要的数据
      tableData: [],
      tableLabel: [
        {
          prop: 'personName',
          label: '姓名',
          width: 120,
          showOverflowTooltip: false
        },
        {
          prop: 'post',
          label: '岗位',
          // minWidth: 120,
          // maxWidth: 200,
          showOverflowTooltip: false
        },
        {
          prop: 'mobileTel',
          label: '移动电话',
          width: 120,
          showOverflowTooltip: false
        },
        {
          prop: 'operating',
          label: '操作',
          fixed: 'right',
          type: 'scope',
          width: 170,
          showOverflowTooltip: false
        }
      ],
      tableTotalSize: null,
      multipleSelection: [],
      currentRow: {}
    }
  },
  methods: {
    // 点击新增或者编辑
    alertForm(type) {
      if (type === 'add') {
        this.dialogTitle = '新增联系人'
      } else {
        this.dialogTitle = '编辑联系人'
        setTimeout(() => {
          this.formData = JSON.parse(JSON.stringify(this.currentRow))
        }, 300)
      }
      this.formDialogType = type
      this.dialogVisible = true
    },
    // 删除
    deleteClick() {
      this.$confirm('此操作将永久删除该联系人, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteClientPerson({ personId: this.currentRow.personId }).then((res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.$refs.myTable.getTableData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    closeDialog() {
      this.formData = {
        personId: null,
        personName: '',
        post: '',
        email: '',
        mobileTel: null,
        telephone: null,
        userNote: '',
        sex: ''
      }
      this.dialogVisible = false
    },
    pageClose() {
      this.$emit('setPageIndex')
    },
    // 提交处理函数
    personSubmit(data, type) {
      data['personType'] = 1
      if (type === 'add') {
        data['companyId'] = this.currentSupplier.id
        addClientPerson(data).then((res) => {
          this.$notify({
            title: '成功',
            message: '增加联系人成功',
            type: 'success'
          })
          this.closeDialog()
          this.$refs.myTable.getTableData()
        })
      } else {
        editClientPerson(data).then((res) => {
          this.$notify({
            title: '成功',
            message: '更新联系人成功',
            type: 'success'
          })
          this.closeDialog()
          this.$refs.myTable.getTableData()
        })
      }
    },
    // 点击提交
    submitForm() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          this.personSubmit(this.formData, this.formDialogType)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重新获取当前选中行的数据
    resetCurrentRow(id) {
      for (const item of this.tableData) {
        if (id === item.personId) {
          this.currentRow = item
        }
      }
    },
    getTableData(cab) {
      this.searchData.params.companyId = this.currentSupplier.id
      getClientPerson(this.searchData).then((res) => {
        this.tableData = res.data
        this.tableTotalSize = res.total_count
        this.resetCurrentRow(this.currentRow.personId)
        cab(res.data)
      })
    },
    // 搜索
    searchClick() {
      this.searchData.currentPage = 1
      this.searchData.params['personName'] = this.search.personName
      this.$refs.myTable.getTableData()
    },
    // 复选框回调函数
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击行回调函数
    rowClickChange(val) {
      this.currentRow = val
    }
  }
}
</script>
<style lang="less" scoped>
@import '../../../styles/pageTableTop.scss';
.supplierPerson {
  height: 100%;
  /deep/label {
    font-weight: 500;
  }
  .closeIcon {
    float: right;
    padding-right: 10px;
    cursor: pointer;
  }
  .el-link + .el-link {
    margin-left: 0;
  }
}
</style>
